package com.aichan.aibi.job.simpleJob;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author mengyu
 * @date 2024/05/29 17:19
 * Caffeine缓存任务类
 */
@Component
@Slf4j
public class CaffeineCacheSchedule {

    @Resource
    private Cache<String, byte[]> cache;

    @Scheduled(cron = "0 */10 * * * *")
    public void checkRateAndCleanUp(){
        CacheStats stats = cache.stats();
        long hitCount = stats.hitCount();
        long missCount = stats.missCount();
        double hitRate = stats.hitRate();
        double missRate = stats.missRate();
        if(missRate >= 0.5){
            log.warn("Caffeine Cache: hitCount:{}, missCount:{}, hitRate:{},missRate:{}",hitCount,missCount,hitRate,missRate);
        }else {
            log.info("Caffeine Cache: hitCount:{}, missCount:{}, hitRate:{},missRate:{}",hitCount,missCount,hitRate,missRate);
        }
        // 清除缓存中被淘汰的数据
        cache.cleanUp();
    }

}
